(function() {
    'use strict';

    /**
     * @ngdoc directive
     * @name webApp.directive:checkedItemList
     * @description
     * # checkedItemList 
     */
    angular.module('webApp')
        .directive('checkedItemList', function() {
            return {
                restrict: 'E',
                templateUrl: "views/directives.checked.item.list.html",
                scope: {},
                controller: ['$templateCache', '$rootScope', '$scope', '$compile', 'dataService', '$timeout', 'helper', 'sku', function($templateCache, $rootScope, $scope, $compile, dataService, $timeout, helper, sku) {
                    //1、事件 2、function 函数接受参数
                    $rootScope.$on('event:checked-item-list', function(event, data) {
                        $scope.activity_id = data.activity_id;
                        $scope.pageData1(1);
                    });

                    //请求数据
                    $scope.itemsTotal = 0;
                    $scope.pageSize = 5;
                    $scope.pageData1 = function(pageNo) {
                        $scope.page_no = pageNo;
                        var query = {};
                        query.query = {
                            "store_id": $rootScope.store_id,
                            "activity_id": $scope.activity_id
                        };

                        dataService.actItemGet(query).then(function(result) {
                            var itemData = {};
                            var activity_items = result.activitys[0] ? result.activitys[0].activity_items : {};

                            async.map(activity_items, function(item, call) {
                                if (itemData[item.item_id]) {
                                    var sku_id = item.sku_id;
                                    itemData[item.item_id][sku_id] = item;
                                } else {
                                    var sku_id = item.sku_id;
                                    itemData[item.item_id] = {};
                                    itemData[item.item_id][sku_id] = {};
                                    itemData[item.item_id][sku_id] = item;
                                }
                                call(null, itemData);
                            }, function(e, r) {
                                var b = [];
                                async.mapSeries(_.keys(itemData), function(num_iid, call) {
                                    dataService.itemGet({
                                        query: {
                                            "item_id": num_iid
                                        }
                                    }).then(function(list) {
                                        list.items[0].dazhe = {};
                                        if (itemData[num_iid][0]) {
                                            list.items[0].dazhe.discount = itemData[num_iid][0].discount;
                                            list.items[0].dazhe.disprice = itemData[num_iid][0].disprice;
                                            list.items[0].dazhe.type_id = itemData[num_iid][0].type_id;
                                            list.items[0].dazhe.id = itemData[num_iid][0].id;
                                            list.items[0].dazhe.item_checked = "item";
                                            list.items[0].dazhe.dazhe_type = "item";

                                            var itemSkus = $scope.updateSkuType(list.items[0]);
                                            list.items[0].newSkus = sku.skuRuCan(itemSkus);
                                            list.items[0].otherSkus = sku.addDazheOtherSkus(list.items[0].skus);

                                        } else {
                                            list.items[0].dazhe.item_checked = 'sku';
                                            list.items[0].dazhe.dazhe_type = 'sku';

                                            var itemSkus = $scope.updateSkuType(list.items[0]);
                                            list.items[0].newSkus = sku.skuRuCan(itemSkus);

                                            list.items[0].otherSkus = sku.addDazheOtherSkus(list.items[0].skus, itemData[num_iid]);
                                        }
                                        b.push(list.items[0]);
                                        call(null, null);
                                    });
                                }, function(e, r) {
                                    $scope.itemslist1 = b;
                                });
                            });
                        });
                    }

                    //商品打折
                    $scope.addItemCuxiao = function(item, flag) {
                        if ($scope.activity_id) {
                            item.activity_id = $scope.activity_id;
                        }

                        if (flag == "item") {
                            var checkedItem = {
                                "partner_id": 1,
                                "activity_id": Number(item.activity_id),
                                "item_id": item.item_id,
                                "type_id": item.dazhe.type_id,
                                "discount": Number(item.dazhe.discount),
                                "disprice": Number(item.dazhe.disprice)
                            };

                            //判断价格是否合法
                            if (checkedItem.discount < 0 || checkedItem.disprice < 0) {
                                helper.myTip("error:请正确输入商品折扣", "#btn-" + item.item_id);
                                return false;
                            }

                            var a = [];
                            a.push(checkedItem);
                        } else {
                            var a = [];
                            for (var i in item.otherSkus) {
                                var sku = {
                                    "partner_id": 1,
                                    "activity_id": Number(item.activity_id),
                                    "item_id": item.item_id,
                                    "sku_id": item.otherSkus[i].sku_id,
                                    "type_id": item.otherSkus[i].dazhe.type_id,
                                    "discount": Number(item.otherSkus[i].dazhe.discount),
                                    "disprice": Number(item.otherSkus[i].dazhe.disprice)
                                };
                                if (sku.discount < 0 || sku.disprice < 0) {
                                    helper.myTip("error:请正确输入商品sku折扣或者价格", "#sku-" + item.item_id);
                                    return false;
                                }
                                a.push(sku);
                            }
                        }
                        var data = {};

                        data.activity_id = $scope.activity_id;
                        data.activity_items = a;

                        //商品打折之前先判断商品是不是参加过其他的活动
                        var query = {
                            "item_id": item.item_id
                        };

                        dataService.actItemGet(query).then(function(act_item) {
                            var itemData = {};
                            _.map(act_item.activity_items, function(item, k) {
                                if (itemData[item.item_id]) {
                                    var sku_id = item.sku_id;
                                    itemData[item.item_id][sku_id] = item;
                                } else {
                                    var sku_id = item.sku_id;
                                    itemData[item.item_id] = {};
                                    itemData[item.item_id][sku_id] = {};
                                    itemData[item.item_id][sku_id] = item;
                                }
                            });

                            var item_id = item.item_id;
                            if (_.keys(itemData).indexOf(item_id) != -1 && _.size(_.keys(itemData))) {
                                helper.myAlert("error:该商品已经参加过其他打折活动");
                                return false;
                            } else {
                                dataService.addItemCuxiao(data).then(function(result) {
                                    if (result.activity_id && flag == "item") {
                                        $scope.DisableItem(item.item_id, flag, item);
                                    } else if (result.activity_id && flag == "sku") {
                                        $scope.DisableItem(item.item_id, flag, item);
                                    } else {

                                    }
                                    $scope.pageData1($scope.page_no);

                                    // var query = {
                                    //     "content": { "store_id": $rootScope.store_id, "item_id": item.item_id, "dazhe_type": "part" }
                                    // };
                                    // $scope.nsqrequest(query);
                                });
                            }
                        });
                    }

                    $scope.nsqrequest = function(data) {
                        dataService.nsqRequest(data).then(function(result) {
                            // console.error("result-->", result);
                        });
                    }

                    //商品退出打折
                    $scope.removeItemCuxiao = function(item, activity_id, id, flag) {
                        if (!id) {
                            helper.myAlert("商品移除错误，返回列表重新进入，移除");
                            return false;
                        }
                        var query = {
                            "id": id,
                            "activity_id": $scope.activity_id
                        };

                        helper.myConfirm('确认删除吗？', function() {

                            if (flag == "sku") {
                                var othersku = {};
                                for (var i in item.otherSkus) {
                                    othersku[item.otherSkus[i].sku_id] = item.otherSkus[i];
                                }
                                if (othersku) {
                                    async.mapSeries(othersku, function(sku, call) {
                                        if (sku.dazhe) {
                                            var iid = sku.dazhe.id;
                                            var query = {
                                                "id": iid,
                                                "activity_id": $scope.activity_id
                                            };
                                            dataService.removeItemCuxiao(query).then(function(data) {
                                                if (data.Err) {
                                                    helper.myAlert("error" + data.Msg);
                                                    return false;
                                                }
                                                call(null, item);
                                            });
                                        }
                                    }, function(e, r) {
                                        $scope.EnableItem(item, 'sku');
                                        $scope.pageData1($scope.page_no);
                                        // var query1 = {
                                        //     "content": {
                                        //         "store_id": $rootScope.store_id,
                                        //         "item_id": item.item_id,
                                        //         "dazhe_type": "part",
                                        //         "delete": 1
                                        //     }
                                        // };
                                        // $scope.nsqrequest(query1);
                                    });
                                }
                            } else {
                                dataService.removeItemCuxiao(query).then(function(data) {
                                    if (data.Err) {
                                        helper.myTip("error" + data.Msg);
                                    } else {
                                        $scope.EnableItem(item, flag);
                                        $scope.pageData1($scope.page_no);

                                        // var query = {
                                        //     "content": {
                                        //         "store_id": $rootScope.store_id,
                                        //         "item_id": item.item_id,
                                        //         "dazhe_type": "part",
                                        //         "delete": 1
                                        //     }
                                        // };
                                        // $scope.nsqrequest(query);
                                    }
                                });
                            }
                        });
                    }

                    //激活1个商品
                    $scope.EnableItem = function(item, flag) {
                        if (flag == 'item') {
                            item.dazhe.item_checked = 'item';
                        } else {
                            item.dazhe.item_checked = 'sku';
                        }

                        item.dazhe.dazhe_type = '';
                    }

                    //禁止1个商品
                    $scope.DisableItem = function(num_iid, flag, item) {
                        if (flag == 'item') {
                            item.dazhe.dazhe_type = 'item';
                        } else {
                            item.dazhe.dazhe_type = 'sku';
                        }
                    }

                    //设置框显示与隐藏 默认隐藏选中商品之后显示 $event, 
                    $scope.showInput = function(num_iid, item) {
                        if ($("#item_" + num_iid).val() == '-') {
                            item.dazhe.item_checked = 'item';
                        } else {
                            item.dazhe.item_checked = 'sku';
                        }
                    }

                    //批量输入框的显示隐藏
                    $scope.freezeBtn = function() {
                        $scope.selectedItemCount();
                        var checkNum = $('.numiidary:checked').length;
                        var statu = checkNum > 0 ? true : false;

                        if (statu) {
                            $("#piLiang").removeClass('zhide');
                        } else {
                            $("#piLiang").addClass('zhide');
                        }
                    }

                    //显示选中了几个商品
                    $scope.selectedItemCount = function() {
                        var checkNum = $('.numiidary:checked').length;
                        $(".selectedItemCount").html(checkNum);
                    }

                    $scope.setType = function(item1, v) {
                        item1.dazhe.type_id = v;
                        $scope.item = item1;
                    }

                    //设置sku的type
                    $scope.setSkuType = function(item2, v, id) {
                        item2.otherSkus[id].dazhe.type_id = v;
                        $scope.item = item2;
                    }

                    //分解sku 组装淘宝格式 显示
                    $scope.updateSkuType = function(itemData) {
                        var fgeoneDate = splitAry(itemData.skus);
                        if (fgeoneDate) {
                            var arr = oneConTwo(fgeoneDate); //将一维数组 转换有父子关系的二维数组
                            var aryData = unique5(arr); //去除重复值；
                            if (aryData) {
                                var newata = [];
                                _.map(aryData, function(dd, kk) {
                                    newata.push({
                                        pid: dd.pid,
                                        name: dd.name,
                                        values: []
                                    });
                                    var len = dd.values;
                                    for (var j = 0; j < len.length; j++) {
                                        if (len[j]) {
                                            newata[kk].values.push(len[j]);
                                        }
                                        if (len.length == j + 1) {
                                            newata[kk].values.push({
                                                id: 0,
                                                value: "",
                                                mark: ""
                                            });
                                        }
                                    }
                                });
                                return newata;
                                // $scope.skuNew = newata;
                                // console.error("skuNew---->", $scope.skuNew);
                            }
                        }
                    }

                    //拆分，切割数组，组成需要是一维数组 
                    function splitAry(skus) {
                        var skusDateAry = [];
                        _.map(skus, function(da, k) {
                            skusDateAry.push({
                                data: da.sku_properties
                            });
                        });
                        var fgeoneDate = [];
                        _.map(skusDateAry, function(dss, kk) {
                            var strs = dss.data.split(";");
                            strs = strs.filter(function(n) {
                                return n
                            });
                            if (strs) {
                                _.map(strs, function(dd, kk) {
                                    var svbtrs = dd.split(":");
                                    if (svbtrs[0] && svbtrs[2] && svbtrs[1] && svbtrs[3]) {
                                        fgeoneDate.push({
                                            pid: Number(svbtrs[0]),
                                            name: svbtrs[2],
                                            id: Number(svbtrs[1]),
                                            value: svbtrs[3]
                                        })
                                    }
                                });
                            }
                        });
                        // console.log("装的数据", fgeoneDate);
                        return fgeoneDate;
                    }

                    //将多个带有父子关系的一维数组，转换为二维数组
                    function oneConTwo(fgeoneDate) {
                        var map = {};
                        var arr = [];
                        for (var i = 0; i < fgeoneDate.length; i++) {
                            var di = fgeoneDate[i];
                            var n = di.pid;
                            if (!map[n]) {
                                //先判断 pid是否有只 有值 先给父级赋值
                                map[n] = di.name;
                                arr.push({
                                    pid: n,
                                    name: di.name,
                                    values: [{
                                        id: di.id,
                                        value: di.value
                                    }]
                                });
                            } else {
                                for (var j = 0; j < arr.length; j++) {
                                    var aj = arr[j];
                                    if (aj.pid == n) {
                                        //pid相等的时候，在给子类赋值
                                        arr[j].values.push({
                                            id: di.id,
                                            value: di.value
                                        });
                                        break;
                                    }
                                }
                            }
                        }
                        return arr;
                    }

                    //去除二维数组中 重复 的一维数组
                    function unique5(arrays) {
                        _.map(arrays, function(arra, k) {
                            var array = arra.values;
                            for (var i = 0, l = array.length; i < l; i++) {
                                for (var j = i + 1; j < l; j++) {
                                    //判断 第一个和第二个数组 内容是否相同 ，id相同 就代表数据相同
                                    if (array[i].id === array[j].id) {
                                        delete arra.values[i];
                                        j = ++i;
                                    }
                                }
                            }
                        });
                        return arrays;
                    }
                }]
            }
        });
})();